package com.tzz.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.tzz.config.CreateActivityConfig;
import com.tzz.dao.PreActivityDao;
import com.tzz.dao.ProductDao;
import com.tzz.dao.StationDao;
import com.tzz.entity.PreActivity;
import com.tzz.entity.Product;
import com.tzz.exception.ActivityNotExistException;
import com.tzz.exception.StationNotInActivityException;
import com.tzz.service.PreActivityService;
import com.tzz.utils.ModelDataUtil;
import com.tzz.utils.ProducerMQUtil;
import com.tzz.utils.RandomUtil;
import com.tzz.vo.StationStop;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class PreActivityServiceImpl implements PreActivityService {
    @Autowired
    PreActivityDao preActivityDao;

    @Autowired
    StationDao stationDao;

    @Autowired
    ProductDao productDao;

    @Autowired
    CreateActivityConfig createActivityConfig;


    @Override
    public int addActivity(PreActivity preActivity) {
//        得到发送的msg数据模板
        JSONObject dataModel = updateCreateActivityModel(preActivity);
//        发送MQ创建活动
        DefaultMQProducer producer = ProducerMQUtil.getProducer(createActivityConfig.getGroup());
        ProducerMQUtil.sendMsg(producer,createActivityConfig.getNameServer(),createActivityConfig.getTopic(),dataModel);
        ProducerMQUtil.producerShutDown(producer);

//        本地库插入活动相关信息：活动、商品、站点
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDateTime = dateFormat.format(new Date(System.currentTimeMillis()));
        preActivity.setCreateTime(currentDateTime);
        preActivityDao.insertActivityStation(preActivity);
        preActivityDao.insertActivitySku(preActivity);
        return preActivityDao.insertPreActivity(preActivity);
    }

    /**
     * 交易侧活动截单
     * */
    @Override
    public void stopActivity(String presaleId,List<Integer> requestStationIds) throws StationNotInActivityException, ActivityNotExistException {
        JSONObject stopActivityDataModel = updateStopActivityModel(presaleId,requestStationIds);
//        PreActivity activityById = preActivityDao.getActivityById(presaleId);

        //        发送MQ截止活动
        DefaultMQProducer producer = ProducerMQUtil.getProducer(createActivityConfig.getGroup());
        ProducerMQUtil.sendMsg(producer,createActivityConfig.getNameServer(),createActivityConfig.getTopic(),stopActivityDataModel);
        ProducerMQUtil.producerShutDown(producer);

//        改变本地库活动数据
        preActivityDao.updateStationActivity(presaleId,requestStationIds);

    }

    @Override
    public PreActivity findActivityById(String activityId) {
        return preActivityDao.getActivityById(activityId);
    }

    @Override
    public List<PreActivity> findAllActivity(String activityId) {
        return preActivityDao.getAllActivity(activityId);
    }

    @Override
    public List<StationStop> findStationStopMapByActivityId(String activityId) {
        return preActivityDao.getStationStop(activityId);
    }

    @Override
    public List<Integer> findSkuIdsByActivityId(String activityId) {
        return preActivityDao.getSkuIdsById(activityId);
    }

    @Override
    public List<Product> findProductsByActivityId(String activityId) {
        List<Integer> skuIds = preActivityDao.getSkuIdsById(activityId);
        return preActivityDao.getProductsBySkuIds(skuIds);
    }


    /**
     * 根据活动ID封装截单请求体
     * */
    private JSONObject updateStopActivityModel(String presaleId,List<Integer> requestStationIds) throws StationNotInActivityException, ActivityNotExistException {
        JSONObject stopActivityDataModel = ModelDataUtil.getRequestDataModel("create_activity");

//        根据活动ID得到关联的站点
        List<Integer> activityStationIds = preActivityDao.getStationIdsById(presaleId);
//        List<String> activityStationMongoIds = stationDao.getStationMongoIdById(activityStationIds);
//        判断请求站点是否参与活动
        for (int i = 0; i < requestStationIds.size(); i++) {
            if(!activityStationIds.contains(requestStationIds.get(i))){
                throw new StationNotInActivityException("站点："+requestStationIds.get(i)+" 未参与活动");
            }
        }

        PreActivity preActivity = preActivityDao.getActivityById(presaleId);
        if (preActivity == null){
            throw new ActivityNotExistException("presaleId "+"活动不存在");
        }
//        根据活动ID得到SKUID 和 mongoIds
        List<Integer> productSkuIds = preActivityDao.getSkuIdsById(presaleId);
        List<String> productIds = productDao.getProductMongoByIds(productSkuIds);

        List<String> stationIds = stationDao.getStationMongoIdById(requestStationIds);

        stopActivityDataModel.put("presaleId",presaleId);
        stopActivityDataModel.put("productIds",productIds);
        stopActivityDataModel.put("productSkuIds",productSkuIds);
        stopActivityDataModel.put("stationIds",stationIds);
        stopActivityDataModel.put("stationOdoIds",requestStationIds);
        stopActivityDataModel.put("deliveryStartDate",preActivity.getDeliveryStartDate());
        stopActivityDataModel.put("deliveryStartDateTimestamp",preActivity.getDeliveryStartDate().getTime());
        stopActivityDataModel.put("deliveryEndDate",preActivity.getDeliveryEndDate());
        stopActivityDataModel.put("deliveryEndDateTimestamp",preActivity.getDeliveryEndDate().getTime());
        long endTimestamp = System.currentTimeMillis();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = dateFormat.format(new Date(endTimestamp));
        stopActivityDataModel.put("endTime",endTime);
        stopActivityDataModel.put("endTimestamp",endTimestamp);
        stopActivityDataModel.put("messageType",1);
        return stopActivityDataModel;
    }

    /**
     * 根据请求信息更新创建活动message
     * */
    private JSONObject updateCreateActivityModel(PreActivity preActivity){
        String presaleId = RandomUtil.getPresaleId();
        //为了在添加成功后，返回该ID
        preActivity.setActivityId(presaleId);

        JSONObject dataModel = ModelDataUtil.getRequestDataModel("create_activity");
        ArrayList<String> productIds = new ArrayList<>();
        for (int i = 0; i < preActivity.getProductSkuIds().size(); i++) {
            String productMongoId = productDao.getProductBySkuId(preActivity.getProductSkuIds().get(i)).getMongoId();
            productIds.add(productMongoId);
        }
        List<Integer> productSkuIds = preActivity.getProductSkuIds();

        ArrayList<String> stationMongoIds = new ArrayList<>();
        for (int i = 0; i < preActivity.getStationIds().size(); i++) {
            String stationMongoCode = stationDao.getStationByCode(preActivity.getStationIds().get(i)).getStationMongoCode();
            stationMongoIds.add(stationMongoCode);
        }

        List<Integer> stationOdoIds = preActivity.getStationIds();
        DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String deliveryStartDate = dateformat.format(preActivity.getDeliveryStartDate());
        long deliveryStartDateTimestamp = preActivity.getDeliveryStartDate().getTime();
        String deliveryEndDate = dateformat.format(preActivity.getDeliveryEndDate());
        long deliveryEndDateTimestamp = preActivity.getDeliveryEndDate().getTime();
        String endTime = dateformat.format(preActivity.getEndTime());
        long endTimestamp = preActivity.getEndTime().getTime();

        dataModel.put("presaleId",presaleId);
        dataModel.put("productIds",productIds);
        dataModel.put("productSkuIds",productSkuIds);
        dataModel.put("stationIds",stationMongoIds);
        dataModel.put("stationOdoIds",stationOdoIds);
        dataModel.put("deliveryStartDate",deliveryStartDate);
        dataModel.put("deliveryStartDateTimestamp",deliveryStartDateTimestamp);
        dataModel.put("deliveryEndDate",deliveryEndDate);
        dataModel.put("deliveryEndDateTimestamp",deliveryEndDateTimestamp);
        dataModel.put("endTime",endTime);
        dataModel.put("endTimestamp",endTimestamp);
        dataModel.put("messageType",preActivity.getIsStop());
        dataModel.put("isSync",Integer.valueOf(preActivity.getIsSync()));
//        Integer.valueOf(preActivity.getIsSync());
        if(preActivity.getIsSync().equals("0")){
            dataModel.put("isSyncDesc","无货模式");
        }else if (preActivity.getIsSync().equals("1")){
            dataModel.put("isSyncDesc","备货模式");
        }
        System.out.println("============dataModel================");
        System.out.println(dataModel);
        return dataModel;
    }



}
